<?php
// 权限验证组件

// 检查用户是否已登录
function checkLogin() {
    if (!isset($_SESSION['user_id'])) {
        header('Location: index.php');
        exit();
    }
}

// 检查用户是否具有指定权限
function hasRole($conn, $user_id, $required_role) {
    $user_roles = getUserRoles($user_id);
    return in_array($required_role, $user_roles);
}

// 权限验证函数
function requireRole($conn, $required_role, $error_message = null) {
    checkLogin();

    $user_id = $_SESSION['user_id'];

    if (!hasRole($conn, $user_id, $required_role)) {
        if ($error_message === null) {
            $error_message = "您没有访问此页面的权限。需要角色：{$required_role}";
        }

        // 记录未授权访问尝试
        error_log("Unauthorized access attempt: User {$user_id} tried to access page requiring {$required_role}");

        // 重定向到权限错误页面或显示错误信息
        $_SESSION['error_message'] = $error_message;
        header('Location: access_denied.php');
        exit();
    }
}

// 检查多个角色中的任意一个
function requireAnyRole($conn, $required_roles, $error_message = null) {
    checkLogin();

    $user_id = $_SESSION['user_id'];
    $user_roles = getUserRoles($user_id);

    $has_permission = false;
    foreach ($required_roles as $role) {
        if (in_array($role, $user_roles)) {
            $has_permission = true;
            break;
        }
    }

    if (!$has_permission) {
        if ($error_message === null) {
            $roles_str = implode(' 或 ', $required_roles);
            $error_message = "您没有访问此页面的权限。需要角色：{$roles_str}";
        }

        error_log("Unauthorized access attempt: User {$user_id} tried to access page requiring one of: " . implode(', ', $required_roles));

        $_SESSION['error_message'] = $error_message;
        header('Location: access_denied.php');
        exit();
    }
}

// 初始化默认管理员权限（user_id = 1236）
function initializeDefaultAdmin($conn) {
    try {
        // 检查是否已存在默认管理员
        $check_sql = "SELECT COUNT(*) as count FROM user_roles WHERE user_id = '1236' AND role = '系统管理员'";
        $result = $conn->query($check_sql);
        $row = $result->fetch_assoc();

        if ($row['count'] == 0) {
            // 插入默认管理员权限
            $insert_sql = "INSERT INTO user_roles (user_id, role, assigned_by, assigned_at) VALUES ('1236', '系统管理员', 'system', CURRENT_TIMESTAMP)";
            $conn->query($insert_sql);
            error_log("Default admin role assigned to user 1236");
        }
    } catch (Exception $e) {
        error_log('Error initializing default admin: ' . $e->getMessage());
    }
}
?>